layui.define(['jquery', "http"], function (exports) {
    var $ = layui.jquery
    var client = null;
    var uploadObj = {
        upload: function (fileName, _file) {
            return uploadFile(fileName, _file);
        }
    }
    initAliYun();

    function initAliYun() {
        var url = "/oa-system/v1/common/oss";
        var request = layui.http.get({url: url});
        request.done(function (resp) {
            var config = resp.result.result;
            client = new OSS.Wrapper({
                region: config.Region,
                secure: true,
                accessKeyId: config.AccessKeyID,
                accessKeySecret: config.AccessKeySecret,
                stsToken: config.SecurityToken,
                bucket: config.Bucket
            });
            //console.log("初始化阿里云上传配置成功")
        })
    }

    function uploadFile(fileName, _file) {
        //console.log(111)
        return client.multipartUpload(fileName, _file, {}).then(function (results) {
            //console.log("results")
            //console.log(results)
            var secUrl = "";
            if (results.res && results.res.requestUrls && results.res.requestUrls.length > 0) {
                var str = results.res.requestUrls[0]
                //console.log(str.indexOf('?'))
                secUrl = str.substr(0, str.indexOf('?'));
                //console.log("secUrl=" + secUrl)
            }
            var url = results.url ? results.url : secUrl
            return url;
        }).catch(function (error) {
            //console.log(error)
        })
    }

    exports('uploadFile', uploadObj);
});
